<?php

namespace App\Admin\Controllers;

use App\Models\AdminUsersRelatedModel;
use App\Models\FinanceExpensesModel;
use App\Models\FinanceIncomeModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;

class ChartController extends AdminController
{
    public function chart(Content $content)
    {
        $userIdArr = AdminUsersRelatedModel::query();
        if(auth()->user()->id === 1) $userIdArr->where('main_id', auth()->user()->id);
        else {
            $user = AdminUsersRelatedModel::query()->where('user_id', auth()->user()->id)->first();
            $userIdArr->where('main_id', $user->main_id);
        }
        $userIdArr = $userIdArr->pluck('user_id')->toArray();

        // 获取当前年份
        $year = date('Y');
        $incomeData = FinanceIncomeModel::query()
            ->selectRaw('SUM(actual_income_amount) as total_income, MONTH(income_date) as month')
            ->where('status', 1)
//            ->whereIn('operate_id', $userIdArr)
            ->whereYear('income_date', $year)
            ->groupBy('month')
            ->pluck('total_income', 'month')
            ->toArray();

        $expenseData = FinanceExpensesModel::query()
            ->selectRaw('SUM(amount) as total_expenses, MONTH(date) as month')
            ->where('status', 1)
//            ->whereIn('operate_id', $userIdArr)
            ->whereYear('date', $year)
            ->groupBy('month')
            ->pluck('total_expenses', 'month')
            ->toArray();
        $months = range(1, 12);
        $income = [];
        $expense = [];

        foreach ($months as $month) {
            $income[] = $incomeData[$month] ?? 0;
            $expense[] = $expenseData[$month] ?? 0;
        }

        return Admin::content(function (Content $content) use ($income, $expense,$months) {
            $content->header($this->title());
            $content->description('员工报表');
            $content->body(view('index.chart', compact('income', 'expense', 'months')));
        });
    }
}
